package com.css.zfzx.fxpg.modules.levelmap.economicLoss.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.zfzx.fxpg.common.utils.VectorDataUtil;
import com.css.zfzx.fxpg.common.utils.ZipDownloadUtil;
import com.css.zfzx.fxpg.modules.levelmap.economicLoss.repository.entity.FxEconomicLossLevelMapEntity;
import com.css.zfzx.fxpg.modules.levelmap.economicLoss.service.FxEconomicLossLevelMapService;
import com.css.zfzx.fxpg.modules.levelmap.economicLoss.viewobjects.FxEconomicLossLevelMapQueryParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author andy
 * @date 2021-01-26
 */
@Slf4j
@RestController
@RequestMapping("/fx/fxEconomicLossLevelMaps")
public class FxEconomicLossLevelMapController {
    @Autowired
    private FxEconomicLossLevelMapService fxEconomicLossLevelMapService;

    //获取配置文件的上传文件路径
    @Value("${file.upload.path}")
    private String uploadPath;

    @GetMapping("/queryFxEconomicLossLevelMaps")
    public RestResponse queryFxEconomicLossLevelMaps(HttpServletRequest request, FxEconomicLossLevelMapQueryParams queryParams) {
        RestResponse response = null;
        try {
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            JSONObject jsonObject = fxEconomicLossLevelMapService.queryFxEconomicLossLevelMaps(queryParams, curPage, pageSize);
            response = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("/queryFxEconomicLossLevelMapsByFileName")
    public RestResponse queryFxEconomicLossLevelMapsByFileName(HttpServletRequest request, FxEconomicLossLevelMapQueryParams queryParams) {
        RestResponse response = null;
        try {
            String sort = request.getParameter("sort"), order = request.getParameter("order");
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            JSONObject jsonObject = fxEconomicLossLevelMapService.queryFxEconomicLossLevelMapsByFileName(queryParams, curPage, pageSize, sort, order);
            response = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("{id}")
    public RestResponse getFxEconomicLossLevelMap(@PathVariable String id) {
        RestResponse response = null;
        try {
            FxEconomicLossLevelMapEntity fxEconomicLossLevelMap = fxEconomicLossLevelMapService.getFxEconomicLossLevelMap(id);
            response = RestResponse.succeed(fxEconomicLossLevelMap);
        } catch (Exception e) {
            String errorMessage = "获取失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @PostMapping
    public RestResponse saveFxEconomicLossLevelMap(@RequestBody FxEconomicLossLevelMapEntity fxEconomicLossLevelMap) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            fxEconomicLossLevelMapService.saveFxEconomicLossLevelMap(fxEconomicLossLevelMap);
            json.put("message", "新增成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "新增失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;

    }

    @PutMapping
    public RestResponse updateFxEconomicLossLevelMap(@RequestBody FxEconomicLossLevelMapEntity fxEconomicLossLevelMap) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            fxEconomicLossLevelMapService.updateFxEconomicLossLevelMap(fxEconomicLossLevelMap);
            json.put("message", "修改成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "修改失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /*
    @DeleteMapping
    public RestResponse deleteRiskLevelMaps(@RequestParam List<String> ids) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            qhRiskLevelMapService.deleteQhRiskLevelMaps(ids);
            json.put("message", "删除成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "删除失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }*/

    @DeleteMapping
    public RestResponse deleteFxEconomicLossLevelMapByFileName(@RequestParam String fileNames) {
        RestResponse response = null;
        JSONObject json = new JSONObject();

        String[] _fileNames = null;
        List<String> params = new ArrayList<>();
        if (fileNames.indexOf(",") >= 0) {
            _fileNames = StringUtils.split(fileNames, ",");
            params = Arrays.asList(_fileNames);
        } else {
            params = Arrays.asList(fileNames);
        }

        try {
            fxEconomicLossLevelMapService.deleteFxEconomicLossLevelMapsByFileName(params);
            json.put("message", "删除成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "删除失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("/deleteFxEconomicLossLevelMapsByFileNames")
    public RestResponse deleteFxEconomicLossLevelMapsByFileNames(@RequestParam String fileNames) {
        RestResponse response = null;
        JSONObject json = new JSONObject();

        String[] _fileNames = null;
        List<String> params = new ArrayList<>();
        if (fileNames.indexOf(",") >= 0) {
            _fileNames = StringUtils.split(fileNames, ",");
            params = Arrays.asList(_fileNames);
        } else {
            params = Arrays.asList(fileNames);
        }

        try {
            fxEconomicLossLevelMapService.deleteFxEconomicLossLevelMapsByFileName(params);
            json.put("message", "删除成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "删除失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @PostMapping("/getFxEconomicLossLevelMaps")
    public RestResponse getFxEconomicLossLevelMaps(HttpServletRequest request, FxEconomicLossLevelMapQueryParams queryParams) {
        RestResponse response = null;
        try {
            JSONObject jsonObject = fxEconomicLossLevelMapService.getFxEconomicLossLevelMaps(queryParams);
            response = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /**
     * 批量上传文件
     *
     * @param files
     * @return
     */
    @PostMapping("/upload")
    public RestResponse uploadSpaceData(@RequestParam("files") MultipartFile[] files, FxEconomicLossLevelMapQueryParams queryParams) {
        //数据校验
        if (files == null && files.length <= 0) {
            return RestResponse.fail("上传失败，请选择文件");
        }
        String province = queryParams.getProvince(), city = queryParams.getCity(), area = queryParams.getArea();
        if ("".equals(province) ) return RestResponse.succeed("请选择场地所在省份!");
        /*if ("".equals(city)) return RestResponse.succeed("请选择场地所在城市!");
        if ("".equals(area)) return RestResponse.succeed("请选择场地所在区县!");*/

        Long count = fxEconomicLossLevelMapService.lookUpFxEconomicLossLevelMaps(queryParams);
        if (count > 0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传数据, 若要上传最新数据请先在【图层管理】功能中删除数据.");

        String levelMapType = queryParams.getLevelMapType();//0: 直接经济损失等级图 1: 死亡人口等级图
        levelMapType = (levelMapType == null ? "error" : (levelMapType.equals("0") ? "直接经济损失" : (levelMapType.equals("1") ? "死亡人口" : "error")));
        String condition = queryParams.getExtend10();//0:50年超越概率2%分区, 1:50年超越概率10%分区, 2:50年超越概率63%分区, 3:100年超越概率1%分区
        String conditionName = (condition == null ? "error" : (condition.equals("0") ? "50_2" : (condition.equals("1") ? "50_10" : (condition.equals("2") ? "50_63" : (condition.equals("3") ? "100_1" : "error")))));

        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();

        String jxfilename = "";
        String dbffilename = "";
        String tifFileName = "";
        String formatDate = VectorDataUtil.getFormatDate();
        //循环处理每一个文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            String fName = oldFileName.substring(0, oldFileName.indexOf(".")), postfix = oldFileName.substring(oldFileName.indexOf("."));
            String prefix = levelMapType + "_"  + conditionName;
            String district = (province == null ? "0" : province) + "_" + (city == null ? "0" : city) + "_" + (area == null ? "0" : area);
            // 上传后文件名
            String newFileName = district + "_" + prefix + "_" + fName + "_" + formatDate + postfix;
            if (newFileName.contains(".shp") && newFileName.endsWith(".shp")) {
                jxfilename = newFileName;
            }
            if (oldFileName.contains(".dbf") && oldFileName.endsWith(".dbf")) {
                dbffilename = newFileName;
            }
            if (oldFileName.contains(".tif") && oldFileName.endsWith(".tif")) {
                tifFileName = newFileName;
            }

            File savefile = new File(uploadPath + newFileName);
            String absolutePath = savefile.getAbsolutePath();
            File absoluteFile = savefile.getAbsoluteFile();
            if (!savefile.getParentFile().exists()) {
                savefile.getParentFile().mkdirs();
            }
            //if (savefile.exists() && savefile.delete()) {
                //return RestResponse.fail("Destination file [" + savefile.getAbsolutePath() + "] already exists and could not be deleted,请手动删除文件");
            //}
            try {
                //file.transferTo(savefile);
                File _file = new File(uploadPath + newFileName);
                FileUtils.copyInputStreamToFile(file.getInputStream(), _file);
                returnMsg.append(oldFileName);
                returnMsg.append(",");
            } catch (IOException e) {
                e.printStackTrace();
                return RestResponse.fail(oldFileName + "上传失败");
            }
        }
        /*
        String[] paramdatas = VectorDataUtil.getFieldName(uploadPath + dbffilename, "GBK");
        if (paramdatas != null && paramdatas.length > 0) {
            String str = qhProbabilityEarthquakeDangerService.judgeFileParams(paramdatas);
            if (str != "" && str != null && str.length() > 0) {
                //todo:删除对应的文件
                return RestResponse.fail("导入数据参数不正确，参数必须包含【" + str + "】");
            }
        } else {
            //todo:删除对应的文件
            return RestResponse.fail("导入的dbf文件参数不能为空。");
        }*/
        if (!(VectorDataUtil.checkCGCS2000(uploadPath + jxfilename, null))) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据及.prj文件.");

        /*double lossNum = -1;
        if (!("".equals(tifFileName))) {
            lossNum = VectorDataUtil.getValueByTIF(uploadPath + tifFileName) * 10000;//0: 直接经济损失等级图 1: 死亡人口等级图
            if (lossNum == -1) return RestResponse.succeed(tifFileName + " 文件解析出现异常, 请检查上传文件及其路径的正确性!");
        }*/

        String resultMsg = returnMsg.substring(0, returnMsg.length() - 1);
        String resMsg = fxEconomicLossLevelMapService.importShapeFile(uploadPath + jxfilename, province, city, area, condition);
        if (resMsg.indexOf("messyCode") != -1) return RestResponse.succeed("导入.dbf文件的属性的第【" + resMsg.split("#")[1] + "】条数据信息有乱码.");
        if (resMsg.indexOf("fieldNullValue") != -1) return RestResponse.succeed("上传文件中字段值存在空值, 请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("levelError") != -1) return RestResponse.succeed("等级值应为阿拉伯数字1~5, 如3. 请检查等级值的正确性.");
        return RestResponse.succeed(resultMsg + "上传成功.<br/>" + resMsg);
    }

    /**
     * 批量下载文件
     *
     * @param response
     * @return
     */
    @GetMapping("/download")
    public RestResponse downloadFile(HttpServletResponse response, FxEconomicLossLevelMapQueryParams queryParams) {
        //获取指定路径下的所有文件名
        File file = new File(uploadPath);
        File[] files = file.listFiles();
        if (files == null) {
            return RestResponse.fail("下载失败，该目录下不存在文件");
        }
        String province = queryParams.getProvince(), city = queryParams.getCity(), area = queryParams.getArea(), affiliatedFileName = queryParams.getAffiliatedFileName();
        //String tempFileName = (province == "" ? "0" : province) + "_" + (city == "" ? "0" : city) + "_" + (area == "" ? "0" : area) + "_" + (affiliatedFileName == "" ? "0" : affiliatedFileName);
        String levelMapType = queryParams.getLevelMapType();//0: 直接经济损失等级图 1: 死亡人口等级图
        String condition = queryParams.getExtend10();//0:50年超越概率2%分区, 1:50年超越概率10%分区, 2:50年超越概率63%分区, 3:100年超越概率1%分区
        String l_c = levelMapType + "_" + condition;

        String tempFileName = affiliatedFileName;
        String _temp = "";
        List<File> _files = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            _temp = files[i].getName();
            //if (_temp.indexOf("ELM_") != -1 && _temp.indexOf(tempFileName) != -1 && _temp.indexOf(province) != -1 && _temp.indexOf(city) != -1 && _temp.indexOf(area) != -1 && _temp.indexOf(l_c) != -1) _files.add(files[i]);
            if (_temp.indexOf(tempFileName) != -1) _files.add(files[i]);
        }
        List<File> zipFiles = _files;
        //List<File> zipFiles = new ArrayList<>(Arrays.asList(files));
        StringBuffer sb = new StringBuffer();
        if (!CollectionUtils.isEmpty(zipFiles)) {
            String zipName = tempFileName + ".zip";
            String msg = ZipDownloadUtil.zipDownload(response, uploadPath, zipName, zipFiles);
            sb.append(msg);
            return null;
        } else {
            /*sb.append("没有可下载文件");
            return RestResponse.succeed(sb);*/
            String zipName = tempFileName + ".zip";
            String msg = ZipDownloadUtil.zipDownload(response, uploadPath, zipName, new ArrayList<File>());
            return null;
        }
    }

    @GetMapping("/download0")
    public RestResponse downloadFile0(HttpServletResponse response, FxEconomicLossLevelMapQueryParams queryParams) {
        //获取指定路径下的所有文件名
        File file = new File(uploadPath);
        File[] files = file.listFiles();
        if (files == null) {
            return RestResponse.fail("下载失败，该目录下不存在文件");
        }
        String province = queryParams.getProvince(), city = queryParams.getCity(), area = queryParams.getArea();
        String tempFileName = "ELM_" + (province == "" ? "0" : province) + "_" + (city == "" ? "0" : city) + "_" + (area == "" ? "0" : area);
        String _temp = "";
        List<File> _files = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            _temp = files[i].getName();
            if (_temp.indexOf(tempFileName) != -1) _files.add(files[i]);
        }
        List<File> zipFiles = _files;
        //List<File> zipFiles = new ArrayList<>(Arrays.asList(files));
        StringBuffer sb = new StringBuffer();
        if (!CollectionUtils.isEmpty(zipFiles)) {
            String zipName = tempFileName + ".zip";
            String msg = ZipDownloadUtil.zipDownload(response, uploadPath, zipName, zipFiles);
            sb.append(msg);
            return null;
        } else {
            /*sb.append("没有可下载文件");
            return RestResponse.succeed(sb);*/
            String zipName = tempFileName + ".zip";
            String msg = ZipDownloadUtil.zipDownload(response, uploadPath, zipName, new ArrayList<File>());
            return null;
        }
    }
}